package org.linlinjava.litemall.admin.service;

import org.linlinjava.litemall.core.util.Util;
import org.linlinjava.litemall.db.dao.TFansMapper;
import org.linlinjava.litemall.db.dao.TMoneyRecordMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.enumeration.Const;
import org.linlinjava.litemall.db.util.Str;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 结算中心业务类
 */
@Service
@Transactional
public class ASettlementCenterService {

    /**
     * 需要一张表记录金额使用的，类型有：营业、邮费、提货佣金、分销佣金、下级分销佣金提成、红包
     *
     * @param order
     */
    public void settlement(TOrder order) {
        Util.runTask(() -> settlement0(order));
    }

    public void settlement0(TOrder order) {
        Integer orderType = order.getOrderType();
        BigDecimal payAmount = order.getPayAmount();
        BigDecimal originPayAmount = payAmount;
        log.info("订单[transNo={}、金额={}]完成，进行结算", order.getTransNo(), payAmount);
        TUser2 shopUser = user2Service.findByShopId(order.getShopId());
        TShop shop = shopService.findById(order.getShopId());
        log.info("商家结算[name={}]增加营业额[{}]到余额", shop.getShopName(), payAmount);
        BigDecimal totalAmount = payAmount.multiply(new BigDecimal(shop.getCommission())).divide(new BigDecimal(100));
        payAmount = payAmount.subtract(totalAmount);
        log.info("计算出总佣金[{}]", totalAmount);
        if (orderType != Const.ORDER_TYPE.TIMELY && totalAmount.doubleValue() >= 0.1) {  //不是及时达订单并且佣金需要大于0.1才给予结算
            String shareCode = order.getShareCode();
            if (!Str.isEmpty(shareCode)) {
                log.info("进行分销结算");
                TUser2 shareUser = user2Service.findByCode(shareCode);
                if (shareUser.getIdentity() > Const.Identity.USER) {
                    BigDecimal A = totalAmount.multiply(new BigDecimal(0.6));
                    totalAmount = totalAmount.subtract(A);
                    log.info("分销商[code={}]结算佣金[{}]的60%[{}]", shareCode, totalAmount, A);
                    addAmount(shareUser, originPayAmount, A, Const.AMOUNT_TYPE.DISTRIBUTION);

                    if (shareUser.getpId() != null) {
                        TUser2 sharePUser = user2Service.findById(shareUser.getpId());
                        BigDecimal C = totalAmount.multiply(new BigDecimal(0.1));
                        log.info("分销商上级[code={}]的结算佣金[{}]的10%[{}]", sharePUser.getCode(), totalAmount, C);
                        totalAmount = totalAmount.subtract(C);
                        Integer type = Const.AMOUNT_TYPE.SUB;
                        if (shareUser.getIdentity() != Const.Identity.DISTRIBUTOR) {
                            type = Const.AMOUNT_TYPE.SUB2;
                        }
                        addAmount(sharePUser, originPayAmount, C, type);
                        //更新粉丝
                        updateFans(shareUser, C);
                    }

                } else {
                    log.info("推荐的用户[code={}]是普通用户，不赚取佣金", shareCode);
                }
            }
            Integer goodsAddressShopId = order.getGoodsAddressId();
            if (goodsAddressShopId != null) {
                log.info("提货点提成");
                BigDecimal B = totalAmount.multiply(new BigDecimal(0.3));
                totalAmount = totalAmount.subtract(B);
                TUser2 addressShopUser = user2Service.findByShopId(goodsAddressShopId);
                log.info("提货商家[code={}]结算佣金[{}]的30%[{}]", addressShopUser.getCode(), totalAmount, B);
                addAmount(addressShopUser, originPayAmount, B, Const.AMOUNT_TYPE.PICKUP);
            }
        }
        payAmount = payAmount.add(totalAmount);
        addAmount(shopUser, originPayAmount, payAmount, Const.AMOUNT_TYPE.NORMAL);
    }


    /**
     * 更新粉丝表
     *
     * @param user   当前用户
     * @param amount 金额
     */
    private void updateFans(TUser2 user, BigDecimal amount) {
        if (amount.doubleValue() > 0.01D) {
            log.info("更新粉丝表[当前用户分销成功后，上级获取提成]");
            // 找到当前用户
            TFans fans = fansMapper.selectOneByExample(TFansExample.newAndCreateCriteria()
                    .andPIdEqualTo(user.getpId()).andUIdEqualTo(user.getId()).example());
            fans.setAmount(fans.getAmount().add(amount));
            fansMapper.updateByPrimaryKey(fans);
        }
    }

    /**
     * 新增记录
     *
     * @param user        当前用户
     * @param totalAmount 销售金额（订单相关）
     * @param amount      金额
     * @param type        类型
     */
    private void addAmount(TUser2 user, BigDecimal totalAmount, BigDecimal amount, Integer type) {
        addAmount0(user, totalAmount, amount, type, null);
    }

    private void addAmount0(TUser2 user, BigDecimal totalAmount, BigDecimal amount, Integer type, String value) {
        if (totalAmount == null)
            totalAmount = new BigDecimal(0);
        if (amount == null)
            amount = new BigDecimal(0);
        log.info("插入金额记录[userId={}、amount={}、type={}]", user.getId(), amount, Const.AMOUNT_TYPE.value(type));
        user.setBalance(user.getBalance().add(amount));
        TMoneyRecord record = TMoneyRecord.builder().totalAmount(totalAmount)
                .amount(amount).type(type).value(value)
                .uId(user.getId()).createdTime(LocalDateTime.now()).build();
        moneyRecordMapper.insert(record);
        user2Service.updateUser(user);
    }




    private static Logger log = LoggerFactory.getLogger(ASettlementCenterService.class);
    @Autowired
    private User2Service user2Service;
    @Autowired
    private ShopService shopService;
    @Autowired
    private TMoneyRecordMapper moneyRecordMapper;
    @Autowired
    private TFansMapper fansMapper;
}
